package com.itheima.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckgroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.service.CheckgroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass =CheckgroupService.class )
@Transactional
public class CheckgroupImpl implements CheckgroupService {
    @Autowired
    private CheckgroupDao checkgroupDao;
    @Override
    public void add(CheckGroup checkGroup, Integer[]checkitemIds) {
         checkgroupDao.add(checkGroup);
       Integer checkGroupId = checkGroup.getId();

       if(checkitemIds!=null&&checkitemIds.length>0){
           for (Integer checkitemId : checkitemIds) {
               Map<String,Integer>map = new HashMap<>();
               map.put("checkGroupId",checkGroupId);
               map.put("checkitemId",checkitemId);
               checkgroupDao.addCheckGroupAndCheckItem(map);
           }
       }

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkgroupDao.findByQueryString(queryString);
        return new PageResult(page.getTotal(),page);
    }

    @Override
    public List<Integer> findCheckItemByCheckGroupId(Integer  id) {
          return checkgroupDao. findCheckItemByCheckGroupId(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        checkgroupDao.edit(checkGroup);
        Integer checkGroupId = checkGroup.getId();
        checkgroupDao.deleteAssociation(checkGroupId);

        if(checkitemIds!=null&&checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                Map<String,Integer>map = new HashMap<>();
                map.put("checkGroupId",checkGroupId);
                map.put("checkitemId",checkitemId);
                checkgroupDao.addCheckGroupAndCheckItem(map);
            }
        }

    }
}
